# -*- coding: utf-8 -*-
import re
from re import match, findall


class Logic:
    def __init__(self):
        
        self._mask = '\{\{\s?([a-zA-Z_-]{3,20}):(.*?)\s\}\}'
        self.hash = {}        
        self.hash = {}
    
    def _load_functions_(self, data_in):       
        
        '''
        Private function that returns the iterations of 
        found possibly valid functions
        '''
        
        data = findall(self._mask, data_in, re.DOTALL )        
        
        for key_function, unparsed_values in data:
            #Yielding tuple
            yield ( key_function, unparsed_values )
            
            
    def build_function_name(self, i, filename):        
        
        '''
        Build Function name. 
        Escaping chars, adding specific number to identify it        
        '''
        
        
        return '%s_%d' % (filename.replace('.', ''), i)
            
    def build(self, filename, data_in):
        
        '''
        Building functions. This method called from templates. 
        Place it in cache
        '''
        
        #Generating function name
        for i, recivedParams in enumerate( self._load_functions_(data_in) ):
                
            prepareToReplace = '{{ %s:%s }}' % ( recivedParams[ 0 ], recivedParams[ 1 ] )
            #Parsing result
            result = self._parse_( self.build_function_name(i, filename), recivedParams[ 0 ], recivedParams[ 1 ].split(','))            
            #Replacing result with function
            data_in = data_in.replace( prepareToReplace, '<<%s>>' % result )
            
        return data_in
        
    def is_variable(self,data):
        
        '''
        Check wether the string is variable
        '''
        
        iVar = match('\s*?\{%(\w{1,30})%\}\s?', data)
        if iVar:
            return iVar.group(1)
            
    def _parse_(self, cache_name, function_name, function_agruments):
        
        '''
        Parsing incoming functions. Checking the variables,
        Collecting into list. 
        And returning to the build function cachename        
        '''
        
                
        MyStatic = []
        MyVariables = []        
        
        
        for agrument in function_agruments:            
            iVariable = self.is_variable( agrument )
            
            if iVariable:            
                MyVariables.append( iVariable )
            
            else:            
                MyStatic.append( agrument )
        
        #Applying to the global hash    
        self.hash[ cache_name  ] = {
            'function'  : function_name,
            'static'    : MyStatic,
            'variables' : MyVariables                                                
        }
        
        
        return cache_name
    
    
            
        
        
        
        
        
        
        
            
        
        
        
        
